/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年05月28日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int m = matrix.size();
        if( m == 0 )
            return res;

        int n = matrix[0].size();
        int up = 0, down = m-1, left = 0, right = n-1;
        while( up <= down && left <= right ){
            for(int i = left; i <= right; i++){ // 从左往右
                res.push_back(matrix[up][i]);
            }
            up++;
            
            for(int i = up; i <= down; i++){ //从上到下
                res.push_back(matrix[i][right]);
            }
            right--;
            
            if(up <= down){
                for(int i = right; i >= left; i--){//从右到左
                    res.push_back(matrix[down][i]);
                }
                down--;
            }

            if(left <= right){
                for(int i = down; i >= up; i--){//从下到上
                    res.push_back(matrix[i][left]);
                }
                left++;
            }

        }

        return res;
    }

};
